package cn.com.cetccst.distribution.action;

import static cn.com.cetccst.distribution.mqtt.Topics.TOPIC_POLICY;
import static cn.com.cetccst.tools.kv.CommonKV.kvStore;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import cn.com.cetccst.datacenter.policy.PolicyRepository;
import cn.com.cetccst.datacenter.policy.entity.PolicyEntity;
import cn.com.cetccst.distribution.business.policy.PolicyParser;
import cn.com.cetccst.network.BaseCallback;
import cn.com.cetccst.distribution.business.policy.Policy;
import cn.com.cetccst.distribution.kv.KVKeys;
import cn.com.cetccst.distribution.mqtt.DistributionMqtt;
import cn.com.cetccst.distribution.mqtt.Message;
import cn.com.cetccst.distribution.network.DistributionHttpRequester;
import cn.com.cetccst.distribution.network.response.CheckInResponse;
import cn.com.cetccst.tools.log.CommonLogger;

public class CheckIn {
    public static void subscribeBusiness(Context context) {
        DistributionMqtt.get().subscribe(TOPIC_POLICY, new DistributionMqtt.Callback() {
            @Override
            public void onMessageArrived(String message) {
                Message<Policy> policyMessage = new Gson().fromJson(message, new TypeToken<Message<Policy>>() {
                }.getType());
                //TODO 这里应该只有一个cmd = "push"的内容，这里做拉取业务，然后持久化数据库
                if (Policy.CMD_PUSH.equals(policyMessage.getPayload().getCmd())) {
                    DistributionHttpRequester.getInstance().requestCheckIn(new BaseCallback<>() {
                        @Override
                        public void onResponse(CheckInResponse data) {
                            if (data != null) {
                                String cid = data.getCid();
                                String policyName = data.getName();
                                boolean isMoreCmd = data.isHasMoreCommand();
                                CommonLogger.debug(policyName + " : " + data.getPayload());
//                                if("commands.restriction.SetAndroidComplianceCmd".equals(policyName)) {
//                                    //TODO 其实不用写 if ，但是很多convertor没有处理
//
//                                }
                                PolicyRepository.getInstance().savePolicy(new PolicyEntity(policyName, data.getPayload()));
                                PolicyParser.Result result = PolicyParser.parse(context, policyName, data.getPayload());
                                sendAck(cid, policyName, result, isMoreCmd, this);
                            } else {
                                //TODO 是否稍微重新请求（几何递增）
                            }
                        }

                        private void sendAck(String cid, String policyName, PolicyParser.Result result, boolean isMoreCmd, BaseCallback<CheckInResponse> checkInCallback) {

                            DistributionHttpRequester.getInstance().requestCheckInAck(cid, policyName, result, new BaseCallback<>() {
                                @Override
                                public void onResponse(JSONObject data) {
                                    if (isMoreCmd) {
                                        DistributionHttpRequester.getInstance().requestCheckIn(checkInCallback);
                                    }
                                    kvStore.encode(KVKeys.KEY_LAST_CHECK_IN_TIME, System.currentTimeMillis());
                                }
                            });
                        }
                    });
                }
            }
        });
    }
}
